<?php
namespace Home\Model;
use Think\Model;

/**
 * 订单表模型
 */
class OrderModel extends BaseModel {

    protected $tableName = 't_order';

    /**
     * 生成新订单
     * @author cheng
     */
    public function saveOrder($data) {
        $result = $this->add($data);
        return $result;
    }
    
    /**
     * 查询订单信息（关联查询订单表、订单商品表和订单收件人地址表）
     * @param type $oid 订单id
     * @author cheng
     */
    public function getOrderProductAddress($oid) {
        $data = $this->alias('p')
                ->field('
                        p.F_ORDER_ID as fOrderId, 
                        p.F_AMOUNT as fAmount, 
                        p.F_USER_ID as fUserId,
                        p.F_CREATE_TIME as fCreateTime, 
                        p.F_STATE as fState, 
                        p.F_HANDLE_TIME as fHandleTime,
                        o.F_RECIEVE_NAME as fRecieveName,
                        o.F_mobile as fMobile,
                        o.f_address as fAddress,
                        tp.F_ORDER_PRODUCT_ID as orderProductId,
                        tp.F_PRODUCT_NAME as productName,
                        tp.F_PRODUCT_ID as productId,
                        tp.F_COUNT as count,
                        tp.F_SINGLE_PRICE as price
                    ')
                ->join('left join t_order_address o on p.F_ORDER_ID = o.F_ORDER_ID')
                ->join('left join t_order_product tp on tp.F_ORDER_ID = p.F_ORDER_ID')
                ->where(['p.F_ORDER_ID' => $oid])
                ->find();
        return $data;
    }
    
    /**
     * 查询订单信息（关联查询订单表、订单商品表和商品表）
     * @param type $oid 订单id
     * @author cheng
     */
    public function getOrderProduct($oid) {
        $data = $this->alias('o')
                ->field('
                        o.F_ORDER_ID,
                        o.F_USER_ID,
                        o.F_AMOUNT,
                        p.F_ORDER_PRODUCT_ID,
                        p.F_PRODUCT_ID,
                        p.F_PRODUCT_NAME,
                        p.F_COUNT,
                        pro.F_PRODUCT_TYPE,
                        pro.F_MESSAGE_NUM,
                        pro.F_PRODUCT_PRICE
                    ')
                ->join('left join t_order_product p ON o.F_ORDER_ID = p.F_ORDER_ID')
                ->join('left join t_product pro ON pro.F_PRODUCT_ID = p.F_PRODUCT_ID')
                ->where(['o.F_ORDER_ID' => $oid])
                ->find();
        return $data;
    }
    
    /**
     * 修改订单状态
     * @param type $oid 订单id
     * @author cheng
     */
    public function saveOrderStatus($oid) {
        //首先查找此订单是否已经支付成功
        $check_order = $this->where(['F_ORDER_ID' => $oid, 'F_STATE' => '002'])->find();
        if ($check_order) { //已付款
            return FALSE;
        } else { //未付款则修改状态为已付款
            $result = $this->where(['F_ORDER_ID' => $oid])->save(['F_STATE' => '002', 'F_HANDLE_TIME' => date('YmdHis')]); //已付款
            return $result;
        }
    }
}
